package cate.game.client;

import cate.game.client.netty.NettyContext;
import easy.java.practice.errorcode.EcException;
import org.apache.commons.lang3.StringUtils;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class ClientContextHolder {

    // Map<cid, ClientContext>
    public final Map<String, ClientContext> cid_cc_map = new ConcurrentHashMap<>();

    public void register(String cid, ClientContext cc) {
        if (cid == null) {
            return;
        }
        cid_cc_map.put(cid, cc);
    }

    public void unregister(String cid) {
        if (cid == null) {
            return;
        }
        cid_cc_map.remove(cid);
    }

    public ClientContext get(String cid) {
        if (cid == null) {
            return null;
        }
        return cid_cc_map.get(cid);
    }

    public boolean contains(String cid){
        return cid_cc_map.containsKey(cid);
    }

    public ClientContext getMust(NettyContext netty) {
        String cid = netty.cid();
        if(StringUtils.isBlank(cid)) {
            throw new EcException("getMust ClientContext but cid is blank");
        }
        ClientContext cc = get(cid);
        if(cc == null) {
            cc = new ClientContext();
            cc.setCid(cid);
            cc.setNetty(netty);
            cc.setActiveTime(System.currentTimeMillis());
            register(cid, cc);
        }
        return cc;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        cid_cc_map.forEach(
                (cid, cc) -> {
                    sb.append("cid:" + cid + " =>" + cc + "\n");
                });
        return sb.toString();
    }
}
